package com.dfbz.controller;

import com.dfbz.constant.Const;
import com.dfbz.entity.User;
import com.dfbz.pojo.Result;
import com.dfbz.pojo.StatusCode;
import com.dfbz.service.LoginService;
import com.dfbz.service.impl.LoginServiceImpl;
import com.dfbz.utils.MailUtil;
import com.dfbz.utils.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@Controller
@RequestMapping("user")
public class LoginController {

    @Autowired
    LoginService loginService;

    //TODO:登录 cookie 校验
    @PostMapping(value = "doLogin")
    @ResponseBody
    public Result doLogin(@RequestBody Map<String, Object> params, HttpSession session, HttpServletResponse response) {
//      校验验证码
        String code = (String) params.get("code");
        if (code != null && !code.equals("")) {
            String SystemCode = (String) session.getAttribute("checkCode");
            if (code.equals(SystemCode)) {
//        校验用户名
                String username = (String) params.get("username");
                if (username != null && !username.equals("")) {
                    User dbUser = loginService.findByUser(username);
                    if (dbUser != null) {
//                     校验密码
                        String password = (String) params.get("password");
                        if (password != null && !password.equals("")) {
                            if (password.equals(dbUser.getPassword())) {
//                             记住我
                                Boolean checked = (Boolean) params.get("checked");
                                if (checked) {
                                    Cookie cookie = new Cookie("userInfo", username);
                                    cookie.setMaxAge(Const.MAX_COOKIE_TIME);
                                    cookie.setPath("/");
                                    response.addCookie(cookie);

                                    session.setAttribute("loginUser", dbUser);
                                    return new Result(false, StatusCode.OK, "登录成功已点击记住", dbUser);
                                } else {
                                    session.setAttribute("loginUser", dbUser);
                                    return new Result(false, StatusCode.OK, "登录成功未点击记住", dbUser);
                                }
                            }
                            return new Result(false, StatusCode.ERROR, "密码错误");
                        }
                        return new Result(false, StatusCode.ERROR, "密码为空");
                    }
                    return new Result(false, StatusCode.ERROR, "用户名错误");
                }
                return new Result(false, StatusCode.ERROR, "用户名为空");
            }
            return new Result(false, StatusCode.ERROR, "验证码不正确");
        }
        return new Result(false, StatusCode.ERROR, "验证码为空");
    }

    @PostMapping(value = "register")
    @ResponseBody
    public Result register(@RequestBody Map<String, Object> param) {
        String password1 = (String) param.get("password1");
        String password2 = (String) param.get("password2");
//        验证密码
        if (password1 != null && !password1.equals("")) {
            if (password2 != null && !password2.equals("")) {
                if (password1.equals(password2)) {
//        验证邮箱
                    String email = (String) param.get("email");
                    if (email != null && !email.equals("")) {
//            验证用户名
                        String username = (String) param.get("username");
                        if (username != null && !username.equals("")) {
                            User dbUser = loginService.findByUser(username);
                            if (dbUser == null) {
                                User user = new User(username, password1, email);
                                loginService.register(user);
                                return new Result(true, StatusCode.ERROR, "注册成功");
                            }
                            return new Result(false, StatusCode.ERROR, "用户名已被注册");
                        }
                        return new Result(false, StatusCode.ERROR, "用户名为空");
                    }
                    return new Result(false, StatusCode.ERROR, "邮箱为空");

                }
                return new Result(false, StatusCode.ERROR, "密码不一致");
            }
        }
        return new Result(false, StatusCode.ERROR, "密码为空");
    }


    /**
     * 发送验证码->邮箱
     *
     * @param email   目标邮箱号
     * @param session 随机码存session
     * @return 响应对象
     */
    @GetMapping(value = "sendCode/{email}/", produces = {"application/json"})
    @ResponseBody
    public Result sendCode(@PathVariable("email") String email, HttpSession session) {
        Integer dbCodecheck = loginService.codeCheck(email);
        if (dbCodecheck > 0) {
            String randomNum = StrUtil.createRandomNum();

            session.setAttribute("sysCode", randomNum);
            session.setAttribute("userEmail", email);
            session.setMaxInactiveInterval(600);
            String context = "您的验证码是：" + randomNum;
            try {
                MailUtil.send(email, "《小标交友》重置密码", context, MailUtil.UNICODE);

            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return new Result(true, StatusCode.OK, "发送成功");
        }
        return new Result(true, StatusCode.OK, "邮箱不存在");
    }


    @RequestMapping("reset")
    @ResponseBody
    public Result reset(@RequestBody Map<String, Object> params, HttpSession session) {
//        校验邮箱
        String email = (String) params.get("email");
        String userEmail = (String) session.getAttribute("userEmail");
        if (email != null && !email.equals("")) {
//            校验验证码
            if (userEmail != null && !userEmail.equals("")) {
                if (email.equals(userEmail)) {
                    String code = (String) params.get("code");
                    if (code != null && !code.equals("")) {
                        String sysCode = (String) session.getAttribute("sysCode");
                        if (code.equals(sysCode)) {
//                    验证密码
                            String newPassword = (String) params.get("newPassword");
                            if (newPassword != null && !newPassword.equals("")) {
                                loginService.save(newPassword, userEmail);
                                session.invalidate();
                                return new Result(true, StatusCode.OK, "重置成功");
                            }
                            return new Result(false, StatusCode.ERROR, "密码为空");
                        }
                        return new Result(false, StatusCode.ERROR, "验证码错误");
                    }
                    return new Result(false, StatusCode.ERROR, "验证码为空");
                }
                return new Result(false, StatusCode.ERROR, "邮箱不一致");
            }
            return new Result(false, StatusCode.ERROR, "验证码超时");
        }
        return new Result(false, StatusCode.ERROR, "邮箱不能为空");
    }

    /**
     * 用户退出 清除cookie
     *
     * @param request  交互请求域
     * @param response 交互响应域
     */
    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
//        清除cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("userInfo")) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }
//        清除session
        HttpSession session = request.getSession();
        session.invalidate();
    }


}
